import { defineStore } from 'pinia'
import { login, logout, getUserInfo } from '@/api/auth'
import router from '@/router'

export const useUserStore = defineStore('user', {
  state: () => ({
    token: localStorage.getItem('token') || '',
    userInfo: null
  }),

  getters: {
    isLoggedIn: (state) => !!state.token,
    username: (state) => state.userInfo?.username
  },

  actions: {
    // 设置token
    setToken(token) {
      this.token = token
      localStorage.setItem('token', token)
    },

    // 清除token
    clearToken() {
      this.token = ''
      localStorage.removeItem('token')
    },

    // 设置用户信息
    setUserInfo(userInfo) {
      this.userInfo = userInfo
    },

    // 登录
    async login(loginData) {
      try {
        console.log('开始登录，参数:', { ...loginData, password: '***' })
        const data = await login(loginData)
        console.log('登录接口返回:', data)

        // 检查数据
        if (!data || !data.token || !data.admin) {
          console.error('登录响应数据不完整:', data)
          throw new Error('登录响应数据不完整')
        }

        const { token, admin } = data
        console.log('解析到的数据:', { token: token.substring(0, 10) + '...', admin })
        
        this.setToken(token)
        this.setUserInfo(admin)
        return data
      } catch (error) {
        console.error('登录过程出错:', error)
        this.clearToken()
        throw error
      }
    },

    // 登出
    async logout() {
      try {
        await logout()
        this.clearToken()
        this.userInfo = null
        router.push('/login')
      } catch (error) {
        console.error('登出失败:', error)
        throw error
      }
    },

    // 获取用户信息
    async getUserInfo() {
      try {
        const data = await getUserInfo()
        console.log('获取用户信息返回:', data)

        if (!data) {
          throw new Error('获取用户信息失败')
        }
        this.setUserInfo(data)
        return data
      } catch (error) {
        console.error('获取用户信息失败:', error)
        this.clearToken()
        throw error
      }
    }
  }
}) 